<template>
    <div class="picking zy-content">
        <div class="searchBox search-box-layout">
            <Row :gutter="24">
                <Col span="6">
                <div>
                    <p class="label">配置方案名称</p>
                    <div class="ipt">
                        <Input type="text" clearable v-model="searchParams.warnName" :placeholder="`${$t('common.inputInfo')}`"
                            class="inputBorder" :maxlength="32" />
                    </div>
                </div>
                </Col>
                <Col span="6">
                <div>
                    <p class="label">状态</p>
                    <div class="ipt">
                        <Select v-model="searchParams.warnStatus" filterable clearable :max-tag-count="1"
                            :placeholder="`${$t('common.selectInfo')}`">
                            <Option value="1" label="启用"></Option>
                            <Option value="0" label="禁用"></Option>
                        </Select>
                    </div>
                </div>
                </Col>
                <Col span="4">
                <div>
                    <p class="label hide-label">&#45;&#45;</p>
                    <div class="ipt">
                        <Button class="search-btn" type="primary" @click="changeNum">{{ $t('common.Query') }}
                        </Button>
                        <Button class="reset-btn" @click="reset()">{{ $t('common.reset') }}
                        </Button>
                    </div>
                </div>
                </Col>
            </Row>
        </div>
        <div class="list-layout mt16">
            <div class="btns clear">
                <span class="title">{{ $t('common.listInformation') }}</span>
                <Button @click="createfaultCodeShowH">{{
                    $t('maintenance.New')
                }}
                </Button>
                <Button @click="getTableColumns(columns)">{{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}</Button>
            </div>
            <div class="tableContent">
                <Table border class="resizable-table" @on-column-width-resize="onColumnWidthResize" ellipsis ref="selection"
                    :columns="columnsList" :data="data" @on-selection-change="onSelectChange">
                    <template slot-scope="{ row }" slot="action">
                        <span class="operationBtn" @click="disabled(row)"><i class="iconfont zy-common-jinyong"></i>{{
                            row.warnStatus == '1'
                            ? $t("禁用") : $t("启用") }}</span>
                        <span class="operationBtn" @click="edit(row)"><i class="iconfont zy-common-bianji"></i>{{
                            $t('maintenance.Edit') }}</span>
                        <span class="operationBtn" @click="deleteRow(row)"><i class="iconfont zy-common-shanchu"></i>{{
                            $t('maintenance.DeleteObj') }}</span>
                    </template>
                    <template slot-scope="{ row }" slot="disabledinfo">
                        <span>{{ disabledList[row.warnStatus] }}</span>
                    </template>
                </Table>
            </div>
            <div class="pageWrap mt16">
                <pageLeftTitle :total="total"/>
                <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
                    @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
            </div>
        </div>

        <Modal :mask-closable="false" v-model="createStatus" :title="addtitle" class="modal-content-item-layout" @on-cancel="cancleOk" width="90%">
            <div class="addProject">
                <Form ref="form" class="formList" :model="formItem" label-position="top" :rules="ruleValidate">
                    <div class="content-item">
                        <span class="content-item-title">{{ $t('推送规则') }}</span>
                        <div class="pd16">
                            <Row :gutter="20">
                                <Col span="8">
                                <FormItem :label="$t('配置方案名称')" prop="warnName">
                                    <Input type="text" v-model="formItem.warnName"
                                        :placeholder="`${$t('common.inputInfo')}`" />
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem :label="$t('点检计划')" prop="planIds">
                                    <Select ref="servicingPlan" v-model="formItem.planIds" filterable multiple
                                        clearable :max-tag-count="3" :placeholder="`${$t('common.selectInfo')}`"
                                        @on-change="servicingPlanChange">
                                        <Option v-for="(item) of planList" :value="item.id" :key="item.id"
                                            :label="item.planName">
                                        </Option>
                                    </Select>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem :label="$t('提前通知时间(s)')" prop="warnAheadGap">
                                    <Input icon="ios-clock-outline" @on-keyup="levelCheck"
                                        v-model="formItem.warnAheadGap" />
                                </FormItem>
                                </Col>
                            </Row>
                            <Row :gutter="20">
                                <Col span="8">
                                <FormItem :label="$t('角色')" prop="roleId">
                                    <Select ref="userSelect" v-model="formItem.roleId" clearable @on-change="roleChange"
                                        :placeholder="`${$t('common.selectInfo')}`">
                                        <Option v-for="item of roleArr" :value="item.id" :key="item.id" :label="item.name">
                                        </Option>
                                    </Select>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem :label="$t('用户')" prop="users">
                                    <Select v-model="formItem.users" clearable multiple :max-tag-count="3"
                                        :remote-method="searchUserlist" :placeholder="`${$t('common.selectInfo')}`">
                                        <Option v-for="item of userArr" :value="item.userId" :key="item.id"
                                            :label="item.realname">
                                        </Option>
                                    </Select>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem :label="$t('描述')" prop="warnDes">
                                    <Input type="text" v-model="formItem.warnDes"
                                        :placeholder="`${$t('common.inputInfo')}`" />
                                </FormItem>
                                </Col>
                            </Row>
                            <Row :gutter="20">
                                <Col span="8">
                                <FormItem :label="$t('通知类型')" prop="msgType">
                                    <CheckboxGroup v-model="formItem.msgType">
                                        <!-- <Checkbox label="1">E-Mail</Checkbox> -->
                                        <!-- <Checkbox label="2">Watch</Checkbox> -->
                                        <Checkbox label="电子邮件">{{ $t('电子邮件') }}</Checkbox>
                                        <Checkbox label="其他">其他</Checkbox>
                                        <!-- <Checkbox label="3">Message</Checkbox> -->
                                    </CheckboxGroup>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem :label="$t('是否禁用')" prop="warnStatus">
                                    <RadioGroup v-model="formItem.warnStatus">
                                        <Radio label="1">{{ $t('是') }}</Radio>
                                        <Radio label="0">{{ $t('否') }}</Radio>
                                    </RadioGroup>
                                </FormItem>
                                </Col>
                            </Row>
                        </div>
                    </div>
                </Form>
            </div>

            <div slot="footer">
                <Button type="default" @click="cancleOk">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" @click="addOk('form')">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>

        <Modal :mask-closable="false" v-model="delFaultCodeShowF" :title="`${$t('maintenance.Deleteremind')}`">
            <Row class="enableContent">
                <Col span="24" class="enableContentInner">
                <img width="95px" src="~images/event/del.png" alt="" />
                </Col>
                <Col span="24" class="enableTips">
                <span>是否确认删除？</span>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" @click="deleteOk">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>
    </div>
</template>
  
<script>
import fileDownload from "js-file-download";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
    name: "rule",
    mixins: [toggleTableOperation],
    data() {
        return {
            createStatus: false,
            addtitle: '',
            disabledList: [ '是','否'],
            roleArr: [],
            userArr: [],
            planList: [],
            ruleValidate: {
                warnName: [
                    { required: true, message: this.$t('common.selectInfo') }
                ],
                planIds: [
                    { required: true, message: this.$t('common.selectInfo'),type:'array' }
                ],
                warnAheadGap: [
                    { required: true, message: this.$t('common.inputInfo') }
                ],
                users: [
                    { required: true, message: this.$t('common.selectInfo'),type:'array' }
                ],
                msgType: [
                    { required: true, message: this.$t('common.selectInfo'),type:'array'}
                ],
                warnStatus: [
                    { required: true, message: this.$t('common.selectInfo') }
                ]
            },
            importExcelState: false,
            deviceNameList: [],
            status: 0,
            confirmId: '',
            delId: '',
            searchParams: {},
            total: 0,
            pageSize: 10,
            pageNum: 1,
            pageSizeOption: [10, 20, 30],
            importVisible: false,
            allCheck: false,
            create: false,
            confirmBatchFaultCodeShowF: false,
            confirmBatchLoading: false,
            confirmFaultCodeShowF: false,
            confirmLoading: false,
            delFaultCodeShowF: false, //是否显示删除弹窗
            delLoading: false,
            delBatchFaultCodeShowF: false,
            delBatchLoading: false,
            formItem: {},
            delIds: [],
            columns: [
                {
                    title: `${this.$t('配置方案名称')}`,
                    key: "warnName",
                    minWidth: 180,
                    align: "center",
                    resizable: true, tooltip: true,
                },
                {
                    title: '点检计划',
                    key: "planName",
                    minWidth: 150,
                    align: "center",
                    resizable: true,
                    tooltip: true,
                },
                {
                    title: `${this.$t('提前通知时间')}`,
                    key: "warnAheadGap",
                    minWidth: 160,
                    align: "center",
                    resizable: true,
                    tooltip: true,
                },
                {
                    title: `${this.$t('接收用户')}`,
                    key: "warnRealname",
                    minWidth: 160,
                    align: "center",
                    resizable: true,
                    tooltip: true,
                },
                {
                    title: `${this.$t('通知类型')}`,
                    key: "msgTypeStr",
                    width: 200,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                },
                {
                    title: `${this.$t('创建人')}`,
                    key: "realname",
                    align: "center",
                    width: 150,
                    tooltip: true,
                    resizable: true,
                },
                {
                    title: `${this.$t('创建时间')}`,
                    key: "createTime",
                    width: 200,
                    align: "center",
                    tooltip: true,
                    resizable: true,
                },
                {
                    title: `${this.$t('是否禁用')}`,
                    key: "warnStatus",
                    slot: "disabledinfo",
                    width: 110,
                    align: "center",
                    resizable: true,
                },
                {
                    title: `${this.$t('common.operation')}`,
                    slot: "action",
                    fixed: 'right',
                    minWidth: 240,
                    align: "center"
                },
            ],
            deviceTypeList: [],
            data: [],
        };
    },
    created() {
        this.getTableColumnsWidth(this.columns)
        this.searchList()
        // this.getFaultCategory("设备类型")
        this.searchRole()
        this.searchPlan()
    },
    mounted() {

    },
    methods: {
        levelCheck(e) {
            e.target.value = e.target.value.replace(/(^\s*)|(\s*$)/g, "");
            const reg = /[^\d.]/g;
            e.target.value = e.target.value.replace(reg, "");
            e.target.value = e.target.value.replace(/^\./g, "");
            e.target.value = e.target.value
                .replace(".", "$#$")
                .replace(/\./g, "")
                .replace("$#$", ".");
            e.target.value = e.target.value.replace(
                /^(\-)*(\d+)\.(\d\d).*$/,
                "$1$2.$3"
            );
        },
        edit(row) {
            this.addtitle = `${this.$t('编辑')}`
            this.axios({
                url:'/dms/moldSpotCheckPlanWarn/getMoldSpotCheckPlanWarnById',
                method:'get',
                params:{
                    id:row.id
                }
            }).then(res=>{
                this.formItem=res.data;
                this.roleChange(this.formItem.roleId)
                this.formItem.planIds = this.formItem.mmoldSpotCheckPlanWarnPlanRefs.map(val =>val.planId)
                this.formItem.users = this.formItem.mmoldSpotCheckPlanWarnUserRefs.map(val => val.userId)
                this.formItem.msgType=this.formItem.msgTypeStr.split(',')
                this.createStatus = true
            })           
        },
        cancleOk() {
            this.createStatus = false
            this.formItem = {}
            this.$refs.form.resetFields()
        },
        servicingPlanChange() {
            let res = [];
            for (let index = 0; index < this.formItem.planIds.length; index++) {
                const data = this.formItem.planIds[index];
                const item = this.planList.find(item => data === item.id).planName;
                res.push(item)
            }
            this.formItem.servicingPlanName = res

        },
        reset() {
            this.searchParams = {};
            this.changeNum();
        },
        disabled(row) {
            let params = {
                id: row.id,
                warnStatus:row.warnStatus == '1' ? '0':'1',
            }
            this.axios({
                url:'/dms/moldSpotCheckPlanWarn/updateStatusById',
                method: 'post',
                params,
            }).then(res => {
                if (res.code === 200) {
                    this.changeNum();
                    this.$Message.success(res.msg);
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        addOk(name) {
            this.$refs[name].validate((valid) => {
                if (!valid) {
                    console.log(valid,'valid');
                    return
                } else {
                    const data={
                        warnName:this.formItem.warnName,
                        warnDes:this.formItem.warnDes,
                        mmoldSpotCheckPlanWarnPlanRefs:this.formItem.planIds.map(item=>{
                            return {
                                planId:item
                            }
                        }),
                        roleId:this.formItem.roleId,
                        warnStatus:this.formItem.warnStatus,
                        msgType:this.formItem.msgType,
                        warnAheadGap:this.formItem.warnAheadGap,
                        mmoldSpotCheckPlanWarnUserRefs:this.formItem.users.map(item=>{
                            return {
                                userId:item
                            }
                        })
                    }
                    if (this.formItem.id) {
                        this.axios({
                            method: 'post',
                            url: "/dms/moldSpotCheckPlanWarn/updateMoldSpotCheckPlanWarn",
                            data:{
                                ...data,
                                id:this.formItem.id,
                            },
                        }).then(res => {
                            if (res.code === 200) {
                                this.changeNum();
                                this.$Message.success(res.msg);
                                this.cancleOk()
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        })
                    } else {
                        this.axios({
                            method: 'post',
                            url: "/dms/moldSpotCheckPlanWarn/addMoldSpotCheckPlanWarn",
                            data,
                        }).then(res => {
                            if (res.code === 200) {
                                this.searchList();
                                this.$Message.success(res.msg);
                                this.cancleOk()
                            } else {
                                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                            }
                        })
                    }
                }
            })
        },
        roleChange(id) {
            // console.log(this.$refs.userSelect.getCheckedNodes());
            this.$set(this.formItem, 'users', [])
            let params = {
                pageNum: 1,
                pageSize: 100,
                id
            }
            this.axios({
                method: 'get',
                url: "/basic/role/getUsersByRoleId",
                params,
            }).then(res => {
                if (res.code === 200) {
                    // res.data.list.forEach(val => val.id = val.userId)
                    this.userArr = res.data.list
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            });
        },
        searchUserlist(key) {
            let params = {
                key
            }
            this.axios({
                method: 'get',
                url: '/basic/user/searchUser',
                params
            }).then(res => {
                if (res.code === 200) {
                    this.userArr = res.data
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
                }
            })
        },
        //角色
        searchRole() {
            let params = {
                pageNum: 1,
                pageSize: 100,
            };
            this.axios({
                method: 'get',
                url: '/basic/role/page',
                params
            }).then(res => {
                if (res.code === 200) {
                    this.roleArr = res.data.list
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        searchPlan() {
            let data = {
                pageNum: 1,
                pageSize: 100,
            };
            this.axios({
                method: 'POST',
                url: '/dms/moldSpotCheckPlan/getMoldSpotCheckPlanList',
                data,
            }).then(res => {
                if (res.code === 200) {
                    this.planList = res.data.records
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        //获取故障数据
        getFaultCategory(name) {
            this.axios({
                method: 'get',
                url: '/dms/faultCategory/basicDict',
                params: { name }
            }).then(res => {
                if (res.code === 200) {

                    if (name === '故障分类') {
                        this.faultCategoryList = res.data.map(item => {
                            if (item.value) return item;
                        })
                    } else if (name === '设备类型') {
                        this.deviceTypeList = res.data.map(item => {
                            if (item.value) return item;
                        })
                    }
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
                }
            })
        },
        deviceNameChange(val) {
            if (val) {
                this.searchParams.deviceType = val
            }
        },
        handleOutRecords() {
            let params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                ids: this.delIds,
                ...this.searchParams
            }
            const filName = '点检项目'
            this.axios({
                method: 'post',
                url: '/dms/dcmMaintainItem/exportItem',
                responseType: 'blob',
                data: params
            }).then(res => {
                fileDownload(res, filName + '.xlsx')
            })
        },
        importExcelChange(val) {
            this.importExcelState = false;
            if (val === 'success') {
                this.changeNum();
                this.$Message.success('导入成功!')
            }
        },
        //下载模板
        exportTemplate() {
            const filName = "点检项目下载模板";
            this.axios({
                method: "get",
                url: "/dms/dcmMaintainItem/downloadTemplate",
                responseType: "blob",
            }).then((res) => {
                fileDownload(res, filName + ".xlsx");
            });
        },
        getDeviceNameList(deviceName) {
            if (deviceName) {
                this.axios({
                    method: 'get',
                    url: '/dms/dcmMaintainItem/selectDeviceNames',
                    params: {
                        deviceName
                    }
                }).then(res => {
                    if (res.code == 200) {
                        this.deviceNameList = res.data.map(val => ({
                            label: val,
                            value: val
                        }))
                    }
                })
            }
        },
        tabsClick(name) {
            this.status = name
            this.delIds = ''
            this.pageNum = 1
            this.searchList()
            // if (name === 0) {
            //     this.$refs.productConfigComponent.searchBtn();
            // } else  if (name === 1){
            //     console.log(this.$$refs);
            //     this.$refs.boxConfigComponent.searchBtn();
            // }else{
            //     this.$refs.shfitconfigComponent.searchBtn();
            // }
        },
        createfaultCodeShowH() {
            // this.formItem.disabled = 0
            this.userArr=[];
            this.addtitle = `${this.$t('新增')}`
            this.createStatus = true
        },
        //确认
        confirm(row) {
            this.confirmId = row.id
            this.confirmFaultCodeShowF = true
        },
        deleteConfirmOk() {
            this.confirmLoading = true
            this.axios({
                method: 'post',
                url: '/dms/servicingNotifySetting/delete',
                data: {
                    id: this.confirmId
                }
            }).then(res => {

                if (res.code === 200) {
                    this.searchList()
                    this.$Message.success(({ content: '确认成功！', duration: 2, closable: true }));
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
                this.confirmLoading = false
                this.confirmFaultCodeShowF = false
            })
        },
        //批量确认
        handleBatchConfirm() {
            this.confirmBatchFaultCodeShowF = true
        },
        deleteBatchConfirmOk() {
            this.confirmBatchLoading = true
            this.axios({
                method: 'post',
                url: '/dms/dcmMaintainItem/batchVerify',
                data: {
                    ids: this.delIds
                }
            }).then(res => {

                if (res.code === 200) {
                    this.searchList()
                    this.$Message.success(({ content: '批量确认成功！', duration: 2, closable: true }));
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
                this.confirmBatchLoading = false
                this.confirmBatchFaultCodeShowF = false
            })
        },
        handleDelete() {
            if (!(this.delIds && this.delIds.length)) {
                this.$Message.warning(({ content: `${this.$t('common.deleteItems')}`, duration: 2, closable: true }));
                return
            }
            this.delFaultCodeShowF = true
        },
        //删除
        deleteRow(row) {
            this.delId = row.id
            this.delFaultCodeShowF = true
        },
        deleteOk() {
            const obj = {
                method: 'POST',
                url: '/dms/moldSpotCheckPlanWarn/delByIds',
                data: [this.delId]
            }
            this.axios(obj).then(res => {
                if (res.code === 200) {
                    this.changeNum()
                    this.$Message.success(({ content: '删除成功！', duration: 2, closable: true }));
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            }).finally(() => {
                this.delFaultCodeShowF = false
            })
        },
        //批量删除
        handleBatchDelete() {
            if (!(this.delIds && this.delIds.length)) {
                this.$Message.error(`${this.$t('common.deleteItems')}`);
                return
            }
            this.delBatchFaultCodeShowF = true
        },
        onSelectChange(selection) {
            let myArray = [];
            selection.map((item) => {
                myArray.push(item.id);
            });

            this.delIds = myArray;
            if (selection.length > 1) {
                this.allCheck = true;
            } else {
                this.allCheck = false;
            }
        },
        handleSearch() {
            this.searchList()
        },
        //分页
        changeNum() {
            this.pageNum = 1;
            this.searchList();
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        searchList() {
            let params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                ...this.searchParams,
            }
            this.axios({
                method: 'post',
                url: '/dms/moldSpotCheckPlanWarn/getMoldSpotCheckPlanWarnList',
                data: params
            }).then(res => {
                if (res.code === 200) {
                    // res.data.list.forEach(val => val.notificationTime = val.notificationTime + 's')
                    this.data = res.data.records

                    this.total = res.data.total
                } else {
                    this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
                }
            })
        },
        batchImport() {
            this.importExcelState = true;
        },
    },
};
</script>
  
<style lang="scss" scoped>
</style>
  